package com.crm.system.service.impl.coursearrange;

import com.beust.jcommander.internal.Lists;
import com.crm.common.exception.BaseException;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.common.util.DateUtil;
import com.crm.common.util.DateUtils;
import com.crm.common.util.QRCodeUtil;
import com.crm.model.entity.coursearrange.CourseArrange;
import com.crm.model.entity.courseregist.CourseConsumeRecord;
import com.crm.model.entity.courseregist.CourseRegistration;
import com.crm.model.entity.finishOrderProduct.FinishOrderProduct;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.courseregist.*;
import com.crm.model.vo.courseregist.*;
import com.crm.model.vo.returnMoney.ProductOfCustomerVO;
import com.crm.service.coursearrange.CourseArrangeDbService;
import com.crm.service.courseregist.CourseProductConsumeDbService;
import com.crm.service.courseregist.CourseRegistDbService;
import com.crm.service.returnMoney.FinishOrderDBservice;
import com.crm.service.sys.UserAccountDbService;
import com.crm.system.service.coursearrange.CourseArrangeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: 排课
 * @Author lixq-f
 * @Date 2021/4/25
 * @Version V1.0
 **/
@Slf4j
@Service
public class CourseArrangeServiceImpl implements CourseArrangeService {

    @Autowired
    private CourseArrangeDbService courseArrangeDbService;
    @Autowired
    private CourseRegistDbService registDbService;
    @Autowired
    private CourseProductConsumeDbService consumeDbService;
    @Autowired
    private FinishOrderDBservice finishOrderDBservice;
    @Autowired
    private UserAccountDbService userAccountDbService;
    //非会员
    private final int PRODUCT_NO_MEMBER = 0;
    //会员
    private final int PRODUCT_MEMBER = 1;


    /**
     * @Description: 获取课程管理列表
     * @Param: [pageIndex, pageSize]
     * @Author: lixq-f
     * @Date: 2021/4/25
     **/
    @Override
    public DhPageInfo<CourseArrange> getCourseManagerList(Integer pageIndex, Integer pageSize, CourseListQO courseListQO) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        List<CourseArrange> rLst = courseArrangeDbService
                .selectListByAccountId((short) StatusCodeEnum.NORMAL_CODE.getState());
        if (CollectionUtils.isEmpty(rLst)) {
            rLst = Lists.newArrayList();
        }
        PageInfo<CourseArrange> pageInfo = new PageInfo<>(rLst);
        return new DhPageInfo<>(pageInfo, rLst);
    }


    @Override
    public DhPageInfo<CourseListVO> getCourseList(Integer pageIndex, Integer pageSize,
                                                  String sortName, String sortOrder, CourseListQO courseListQO) {

        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        List<CourseListVO> rLst = courseArrangeDbService.selectCourseList(courseListQO, getOrder(sortName, sortOrder));
        if (CollectionUtils.isEmpty(rLst)) {
            rLst = Lists.newArrayList();
        }
        //检查课程状态
        checkCourseStatus(rLst);

        PageInfo<CourseListVO> pageInfo = new PageInfo<>(rLst);
        return new DhPageInfo<>(pageInfo, rLst);
    }


    private void checkCourseStatus(List<CourseListVO> rLst) {
        Date currentDate = DateUtils.parse(DateUtil.getDate("yyyy-MM-dd HH:mm"));
        for (CourseListVO c : rLst) {
            CourseArrange upCourse = new CourseArrange();
            upCourse.setCourseArrangeId(c.getCourseArrangeId());
            Date enterStartTm = c.getEnterStartTm();
            Date enterEndTm = c.getEnterEndTm();
            Date courseStartTm = c.getCourseStartTm();
            if (currentDate.before(enterStartTm)){
                upCourse.setCourseStatus((short) 0);
               c.setCourseStatus("未开始");
            }
            else if (currentDate.after(enterStartTm) && currentDate.before(enterEndTm)){
                upCourse.setCourseStatus((short) 1);
                c.setCourseStatus("报名期");
            }
            else if (currentDate.after(enterEndTm) && currentDate.before(courseStartTm)){
                upCourse.setCourseStatus((short) 2);
                c.setCourseStatus("报名结束");
            }
            else if (currentDate.after(courseStartTm)){
                upCourse.setCourseStatus((short) 3);
                c.setCourseStatus("已完成");
            }
            else {
                upCourse.setCourseStatus(null);
                c.setCourseStatus("未知");
            }
            courseArrangeDbService.update(upCourse);

        }

    }


    private String getOrder(String sortName, String sortOrder) {
        String order = " create_tm desc";
        if (StringUtils.isEmpty(sortName) && StringUtils.isEmpty(sortOrder)) {
            return order;
        }
        if ("courseName".equals(sortName)) {
            order = " course_name " + sortOrder;
        }
        if ("createTm".equals(sortName)) {
            order = " create_tm " + sortOrder;
        }

        return order;
    }


    /**
     * @Description: 添加报名人
     * @Param: [regist]
     * @Return: java.lang.Boolean
     * @Author: lixq-f
     * @Date: 2021/4/26
     **/
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    @Override
    public Boolean insert(CourseRegistQO registQO) {
        /*CourseArrange course =
                courseArrangeDbService.getCourseById(registQO.getCourseArrangeId());*/
        UserAccount userAccount = (UserAccount) SecurityUtils
                .getSubject().getPrincipal();

        List<String> applyNames = registQO.getApplyNames();
        List<String> contactWays = registQO.getContactWays();
        if (applyNames.contains(null) || contactWays.contains(null)) {
            throw new BaseException("参课人或联系方式不可为空！");
        }


        //如果再次添加报名人需要先删除之前报名信息，再重新分配卡次及重新添加报名人
        List<String> registList = registQO.getRegistList();
        if (!CollectionUtils.isEmpty(registList)) {
            delBeforeRegists(registList);
        }

        /**
         * 卡次校验
         */
        //课程报名每人所需次数
        Integer courseServiceTimes = registQO.getCourseServiceTimes();
        //客户报名所需总次数
        Integer requiredTotalTimes = courseServiceTimes * applyNames.size();

        //获取产品信息
        List<CourseProductQO> products = registQO.getProduct();
        List<CourseProductQO> menberList = products.stream()
                .filter(p -> PRODUCT_MEMBER == p.getProductCategories())
                .collect(Collectors.toList());
        int memberSize = menberList.stream().mapToInt(CourseProductQO::getServiceTimes).sum();
        //非会员卡次数(一张非会员卡可以用于一人)
        int noMenberSize = products.size() - menberList.size();
        //产品可用总次数
        int productTotalSize = memberSize + noMenberSize;

        if (requiredTotalTimes > productTotalSize) {
            throw new BaseException("产品服务次数不足！");
        }

        List<CourseProductQO> noMemberList = null;
        if (noMenberSize > 0) {
            noMemberList = products.stream()
                    .filter(p -> PRODUCT_NO_MEMBER == p.getProductCategories())
                    .collect(Collectors.toList());
        }

        /**
         * 写入报名人信息
         */
        List<CourseConsumeRecord> recordList = Lists.newArrayList();
        List<CourseRegistration> registLst = Lists.newArrayList();
        CourseRegistration regist = null;
        CourseConsumeRecord record = null;

        int memberIndex = 0;//从会员列表先取出第一个会员卡进行消费
        Integer serviceTimes = 0;//获取该会员卡剩余服务次数
        CourseProductQO courseProductQO = null;
        if (!CollectionUtils.isEmpty(menberList)) {
            //其次使用会员卡,从第一张会员卡开始扣次
            courseProductQO = menberList.get(memberIndex);
            serviceTimes = courseProductQO.getServiceTimes();
        }

        for (int i = 0; i < applyNames.size(); i++) {
            regist = new CourseRegistration();
            BeanUtils.copyProperties(registQO, regist);
            //生成报名ID
            String courseRegistrationId = CommonUtils.getGUID();
            Date sysDate = DateUtil.getSysDate();
            regist.setCourseRegistrationId(courseRegistrationId);
            regist.setApplyName(applyNames.get(i));
            regist.setContactWay(contactWays.get(i));
            regist.setCreateTm(sysDate);
            regist.setIsSign((short)0);//默认未签到
            regist.setRegistStatus(0);//默认报名中
            regist.setIsConsume((short)0);//默认未划扣
            regist.setCourseType(0);//0-正式参课; 1-试听参课
            regist.setCreatePeopleId(userAccount.getAccountId());
            regist.setCompanyId(userAccount.getCompanyId());
            regist.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
            registLst.add(regist);

            /**
             * 写入卡次消费记录
             */
            if (!CollectionUtils.isEmpty(noMemberList) && i < noMemberList.size()) {
                //非会员卡，优先使用
                CourseProductQO productQO = noMemberList.get(i);
                record = generateConsumeRecord(productQO, sysDate, userAccount, courseRegistrationId, registQO);
                record.setConsumeServiceTimes(1);
                recordList.add(record);
            } else {
                if (serviceTimes >= courseServiceTimes) {
                    //1、会员卡剩余次数足够使用
                    record = generateConsumeRecord(courseProductQO, sysDate, userAccount, courseRegistrationId, registQO);
                    record.setConsumeServiceTimes(courseServiceTimes);
                    recordList.add(record);
                    //减掉已使用的服务次数
                    serviceTimes = serviceTimes - courseServiceTimes;
                } else {
                    //2、会员卡剩余服务次数不够以扣除一个人的报名次数情况
                    //获取剩下还要扣得次数

                    if (serviceTimes == 0) {
                        //该张会员卡已扣完，获取下一张
                        memberIndex = ++memberIndex;
                        courseProductQO = menberList.get(memberIndex);
                        serviceTimes = courseProductQO.getServiceTimes();
                        if (serviceTimes >= courseServiceTimes) {
                            record = generateConsumeRecord(courseProductQO, sysDate, userAccount, courseRegistrationId, registQO);
                            record.setConsumeServiceTimes(courseServiceTimes);
                            recordList.add(record);
                        } else { // 2 < 5
                            record = generateConsumeRecord(courseProductQO, sysDate, userAccount, courseRegistrationId, registQO);
                            record.setConsumeServiceTimes(serviceTimes);
                            recordList.add(record);
                            int usedTimes = courseServiceTimes - serviceTimes;// 3 = 5 - 2
                            while (usedTimes > 0) { //3
                                //该张会员卡已扣完，获取下一张
                                memberIndex = ++memberIndex;
                                courseProductQO = menberList.get(memberIndex);
                                serviceTimes = courseProductQO.getServiceTimes();
                                record = generateConsumeRecord(courseProductQO, sysDate, userAccount, courseRegistrationId, registQO);
                                if (serviceTimes >= usedTimes) { //
                                    record.setConsumeServiceTimes(usedTimes);
                                    recordList.add(record);
                                    break;
                                } else {// 2 < 3
                                    record = generateConsumeRecord(courseProductQO, sysDate, userAccount, courseRegistrationId, registQO);
                                    record.setConsumeServiceTimes(serviceTimes);
                                    recordList.add(record);
                                    usedTimes = usedTimes - serviceTimes;
                                }
                            }

                        }
                    } else {
                        record = generateConsumeRecord(courseProductQO, sysDate, userAccount, courseRegistrationId, registQO);
                        record.setConsumeServiceTimes(serviceTimes);
                        recordList.add(record);
                        int usedTimes = courseServiceTimes - serviceTimes;// 3 = 5 - 2
                        while (usedTimes > 0) { //1
                            //该张会员卡已扣完，获取下一张
                            memberIndex = ++memberIndex;
                            courseProductQO = menberList.get(memberIndex);
                            serviceTimes = courseProductQO.getServiceTimes();
                            record = generateConsumeRecord(courseProductQO, sysDate, userAccount, courseRegistrationId, registQO);
                            if (serviceTimes >= usedTimes) { //
                                record.setConsumeServiceTimes(usedTimes);
                                recordList.add(record);
                                break;
                            } else {// 2 < 3
                                record = generateConsumeRecord(courseProductQO, sysDate, userAccount, courseRegistrationId, registQO);
                                record.setConsumeServiceTimes(serviceTimes);
                                recordList.add(record);
                                usedTimes = usedTimes - serviceTimes;
                            }
                        }

                    }
                }
            }

        }
        consumeDbService.batchInsert(recordList);
        return registDbService.batchInsert(registLst);
    }


    /**
     * @Description:
     * @Param: [registList, courseArrangeId]
     * @Return: void
     * @Author: lixq-f
     * @Date: 2021/6/11
     **/
    private void delBeforeRegists(List<String> registList) {
        for (String registId : registList) {
            consumeDbService.deleteConsumeRecordByRegistId(registId);
            registDbService.deleteById(registId, (short) StatusCodeEnum.DELETE_CODE.getState());
        }


    }


//    private void


    /**
     * 生成消费记录（不含消费次数）
     *
     * @param courseProductQO
     * @param sysDate
     * @param userAccount
     * @param courseRegistrationId
     * @param registQO
     * @return
     */
    private CourseConsumeRecord generateConsumeRecord(CourseProductQO courseProductQO, Date sysDate, UserAccount userAccount,
                                                      String courseRegistrationId, CourseRegistQO registQO) {
        CourseConsumeRecord record = new CourseConsumeRecord();
        BeanUtils.copyProperties(courseProductQO, record);
        record.setCreateTm(sysDate);
        record.setAccountId(userAccount.getAccountId());
        record.setConsumeRecordId(CommonUtils.getGUID());
//        record.setConsumeStatus(0);
        record.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
        record.setCourseArrangeId(registQO.getCourseArrangeId());
        record.setCourseRegistrationId(courseRegistrationId);
        return record;
    }


    @Override
    public Boolean update(EditCourseRegistQO registQO) {
        UserAccount userAccount = (UserAccount) SecurityUtils
                .getSubject().getPrincipal();
        CourseRegistration reg = new CourseRegistration();
        BeanUtils.copyProperties(registQO, reg);
        reg.setUpdateTm(DateUtil.getSysDate());
        reg.setUpdatePeopleId(userAccount.getAccountId());
        return registDbService.update(reg);
    }

    @Override
    public CourseRegistVO selectCourseRegById(String id) {
        return registDbService.selectCourseRegById(id);
    }


    /**
     * @Description: 用户取消报名
     * @Param: [registId, courseId]
     * @Return: java.lang.Boolean
     * @Author: lixq-f
     * @Date: 2021/7/21
    **/
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    @Override
    public Boolean deleteById(String registId, String courseId) {

        if (StringUtils.isEmpty(registId) || StringUtils.isEmpty(courseId)) {
            return false;
        }
        UserAccount userAccount = (UserAccount) SecurityUtils
                .getSubject().getPrincipal();
        consumeDbService.deleteConsumeRecordByRegistId(registId);
        return registDbService.registCancel(userAccount.getAccountId(), DateUtil.getSysDate(), registId);
    }

    @Override
    public DhPageInfo<CourseRegistVO> selectCourseRegistList(Integer pageIndex, Integer pageSize,
                                                             String sortName, String sortOrder,
                                                             CourseRegistListQO registListQO) {

        //先更新课程状态
        List<CourseListVO> courseList = courseArrangeDbService.selectCourseList(new CourseListQO(), null);
        if (!CollectionUtils.isEmpty(courseList)) {
            //检查课程状态
            checkCourseStatus(courseList);
        }

        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        UserAccount userAccount = (UserAccount) SecurityUtils
                .getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());
        List<CourseRegistVO> rLst = null;
        if (Objects.nonNull(registListQO.getBs())) {
            if (registListQO.getBs() == 0) {
                if (rs) {//超管
                } else {//普管
                    registListQO.setCompanyId(userAccount.getCompanyId());
                }
            } else {//普通用户
                registListQO.setAccountId(userAccount.getAccountId());
            }
        }

        rLst = registDbService
                .selectCourseRegistList((short) StatusCodeEnum.NORMAL_CODE.getState(), getRegistOrder(sortName, sortOrder), registListQO);

        if (CollectionUtils.isEmpty(rLst)) {
            rLst = Lists.newArrayList();
        }

        PageInfo<CourseRegistVO> pageInfo = new PageInfo<>(rLst);
        return new DhPageInfo<>(pageInfo, rLst);
    }


    private String getRegistOrder(String sortName, String sortOrder) {
        String order = " r.create_tm desc";
        if (StringUtils.isEmpty(sortName) && StringUtils.isEmpty(sortOrder)) {
            return order;
        }
        if ("registStatus".equals(sortName)) {
            order = " r.regist_status " + sortOrder;
        }
        if ("createTm".equals(sortName)) {
            order = " r.create_tm " + sortOrder;
        }
        return order;
    }


    /**
     * @Description: 审核取消
     * @Param: [cancelVO]
     * @Return: java.lang.Boolean
     * @Author: lixq-f
     * @Date: 2021/6/9
     **/
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    @Override
    public Boolean auditCancel(AuditCancelVO cancelVO) {

        if (null != cancelVO.getIsConsume() && cancelVO.getIsConsume() == 1){
            List<CourseConsumeRecord> consumeRecords =
                    consumeDbService.getConsumeRecordByRegistId(cancelVO.getRegistId());
            if (!CollectionUtils.isEmpty(consumeRecords)){
                for (CourseConsumeRecord consumeRecord : consumeRecords) {
                    if (consumeRecord.getProductCategories() == 0){
                        //非会员卡
                        finishOrderDBservice.updateServiceTimesByProductNum(consumeRecord.getProductNum(), 1);
                    }
                    //会员卡
                    else {
                        FinishOrderProduct product = finishOrderDBservice.getProductByProductNum(consumeRecord.getProductNum());
                        finishOrderDBservice.updateServiceTimesByProductNum(consumeRecord.getProductNum(),
                                product.getProductStrokesServiceNumber() + consumeRecord.getConsumeServiceTimes());
                    }
                }
            }

        }

        UserAccount userAccount = (UserAccount) SecurityUtils
                .getSubject().getPrincipal();
        Date sysDate = DateUtil.getSysDate();
        CourseRegistration regist = new CourseRegistration();
        regist.setCourseRegistrationId(cancelVO.getRegistId());
        regist.setCancelReason(cancelVO.getCancelReason());
        regist.setCancelType(1);//审核取消
        regist.setRegistStatus(2);//报名状态为已取消
        regist.setCancelPerson(userAccount.getAccountId());
        regist.setCancelTm(sysDate);
        consumeDbService.deleteConsumeRecordByRegistId(cancelVO.getRegistId());
        return registDbService.auditCancel(regist);
    }


    /**
     * @Description: 根据客户ID、课程ID获取报名人
     * @Param: [customerId, courseId]
     * @Return: com.crm.common.model.DataResponse
     * @Author: lixq-f
     * @Date: 2021/6/10
     **/
    @Override
    public List<CourseRegistration> getRegistByCourseIdAndCustomerId(String customerId, String courseId) {
        List<CourseRegistration> registList = registDbService.getRegistByCourseIdAndCustomerId(customerId, courseId);
        if (CollectionUtils.isEmpty(registList)) {
            registList = Lists.newArrayList();
        }
        return registList;
    }


    /**
     * @Description: 一键划扣，扣次
     * @Param: [courseId, registList]
     * @Return: java.lang.Boolean
     * @Author: lixq-f
     * @Date: 2021/6/11
     **/
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    @Override
    public Boolean courseConsume(CourseConsumeVO consumeVO) {

        if (CollectionUtils.isEmpty(consumeVO.getRegistList())) {
            throw new BaseException("请先选择报名人！");
        }
        //获取待审核报名人扣次记录
        List<CourseConsumeRecordVO> courseConsumeLst =
                consumeDbService.queryRecordsByRegistsId(consumeVO.getRegistList());

        if (CollectionUtils.isEmpty(courseConsumeLst)) {
            throw new BaseException("请选择待审核的报名人！");
        }
        //消费非会员卡
        consumeNoMember(courseConsumeLst);

        //消费会员卡
        consumeMember(courseConsumeLst);

        return true;
    }


    /**
     * @Description: 消费会员卡
     * @Param: [courseConsumeLst]
     * @Return: void
     * @Author: lixq-f
     * @Date: 2021/6/11
     **/
    private void consumeMember(List<CourseConsumeRecordVO> courseConsumeLst) {
        List<CourseConsumeRecordVO> memberList = courseConsumeLst.stream()
                .filter(c -> c.getProductCategories() == 1)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(memberList)){
            return;
        }

        List<String> productNumLst = memberList.stream().map(c -> c.getProductNum())
                .collect(Collectors.toList());
        List<ProductOfCustomerVO> productLst =
                finishOrderDBservice.queryProductsByProductNumLst(productNumLst);
        Map<String, ProductOfCustomerVO> productMap = productLst
                .stream()
                .collect(Collectors.toMap(ProductOfCustomerVO::getFinishOrderProductNum, Function.identity()));

        Map<String, Integer> memberMap = memberList
                .stream().collect(Collectors.groupingBy(CourseConsumeRecordVO::getProductNum,
                        Collectors.summingInt(CourseConsumeRecordVO::getConsumeServiceTimes)));

        for (Map.Entry<String, Integer> entry : memberMap.entrySet()) {
            String productNum = entry.getKey();
            Integer serviceTimeTotal = entry.getValue();
            ProductOfCustomerVO product = productMap.get(productNum);
            Integer productServiceTimes = product.getServiceNumber();
            List<String> registLst = courseConsumeLst
                    .stream().filter(c -> productNum.equals(c.getProductNum()))
                    .map(p -> p.getCourseRegistrationId()).collect(Collectors.toList());
            if (serviceTimeTotal > productServiceTimes){
                //审核未通过，且为取消类型为次数不够取消
                registDbService.updateRegistStatusByRegistIds(registLst, 2, 2, 0);
                log.info("当前卡服务次数不足，卡号为:{} ", productNum);
            }else {
                finishOrderDBservice.updateServiceTimesById(product.getFinishOrderProductId(), productServiceTimes - serviceTimeTotal);
                registDbService.updateRegistStatusByRegistIds(registLst, 1, 0, 1);
            }

        }

    }


    /**
     * @Description: 消费非会员卡
     * @Param: [courseConsumeLst]
     * @Return: void
     * @Author: lixq-f
     * @Date: 2021/6/11
    **/
    private void consumeNoMember(List<CourseConsumeRecordVO> courseConsumeLst) {
        List<CourseConsumeRecordVO> noMemberList = courseConsumeLst
                .stream().filter(c -> c.getProductCategories() == 0)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(noMemberList)){
            return;
        }

        List<String> productNumLst = noMemberList
                .stream().map(c -> c.getProductNum())
                .collect(Collectors.toList());

        List<String> registLst = noMemberList
                .stream().map(c -> c.getCourseRegistrationId()).distinct()
                .collect(Collectors.toList());
        //消费订单完成表
        finishOrderDBservice.consumeNoMember(productNumLst);
        //更新报名表报名状态为报名成功
        registDbService.consumeNoMember(registLst);
    }


    /**
     * @Description: 生成二维码
     * @Param: []
     * @Return: java.lang.String
     * @Author: lixq-f
     * @Date: 2021/7/12
     **/
    @Override
    public String generateQrCode() {

        return QRCodeUtil.creatRrCode(null, 200, 200);
    }


    /**
     * @Description: 审核报名列表
     * @Param: [pageIndex, pageSize, sortName, sortOrder, registListQO]
     * @Return: com.crm.common.model.DataResponse
     * @Author: lixq-f
     * @Date: 2021/7/15
     **/
    @Override
    public DhPageInfo<AuditRegistListVO> selectAuditRegistList(Integer pageIndex, Integer pageSize,
                                                               String sortName, String sortOrder,
                                                               AuditRegistListQO registListQO) {
        //先更新课程状态
        List<CourseListVO> courseList = courseArrangeDbService.selectCourseList(new CourseListQO(), null);
        if (!CollectionUtils.isEmpty(courseList)) {
            //检查课程状态
            checkCourseStatus(courseList);
        }

        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        List<AuditRegistListVO> registList = registDbService.selectAuditRegistList(getRegistOrder(sortName, sortOrder), registListQO);
        if (CollectionUtils.isEmpty(registList)) {
            registList = Lists.newArrayList();
        }
        List<UserAccount> allAccountList = userAccountDbService.getAllAccountList();
        Map<String, String> allAccountMap = null;
        if (!CollectionUtils.isEmpty(allAccountList)){
            allAccountMap = allAccountList
                    .stream()
                    .collect(Collectors.toMap(UserAccount::getAccountId, u -> Optional.ofNullable(u.getUserName()).orElse("")));
        }

        for (AuditRegistListVO registListVO : registList) {
            if(Objects.nonNull(allAccountMap) && StringUtils.isNotEmpty(allAccountMap.get(registListVO.getCancelPerson()))){
                registListVO.setCancelPersonName(allAccountMap.get(registListVO.getCancelPerson()));
            }
        }

        PageInfo<AuditRegistListVO> pageInfo = new PageInfo<>(registList);
        return new DhPageInfo<>(pageInfo, registList);
    }


    /**
     * @Description: 申请试听
     * @Param: [courseTryListenVO]
     * @Return: java.lang.Boolean
     * @Author: lixq-f
     * @Date: 2021/7/26
     **/
    @Override
    public Boolean addCourseTryListen(CourseTryListenVO courseTryListenVO) {

        List<String> applyNames = courseTryListenVO.getApplyNames();
        List<String> contactWays = courseTryListenVO.getContactWays();
        if (applyNames.contains(null) || contactWays.contains(null)) {
            throw new BaseException("参课人或联系方式不可为空！");
        }

        UserAccount userAccount = (UserAccount) SecurityUtils
                .getSubject().getPrincipal();

        List<CourseRegistration> registLst = Lists.newArrayList();
        CourseRegistration regist = null;
        for (int i = 0; i < applyNames.size(); i++){
            regist = new CourseRegistration();
            //生成报名ID
            String courseRegistrationId = CommonUtils.getGUID();
            Date sysDate = DateUtil.getSysDate();
            regist.setCourseRegistrationId(courseRegistrationId);
            regist.setCourseType(1);//0-正式参课; 1-试听参课
            regist.setCreatePeopleId(userAccount.getAccountId());
            regist.setCreateTm(sysDate);
            regist.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
            regist.setCompanyId(userAccount.getCompanyId());
            regist.setRegistStatus(1);//报名成功
            regist.setIsSign((short)0);//默认未签到
            regist.setApplyName(applyNames.get(i));
            regist.setContactWay(contactWays.get(i));
            regist.setRemark(courseTryListenVO.getRemark());
            regist.setCustomerId(courseTryListenVO.getCustomerId());
            regist.setCourseArrangeId(courseTryListenVO.getCourseArrangeId());

            registLst.add(regist);
        }

        return registDbService.batchInsert(registLst);
    }


}
